package com.hoshiicloud.as2c.minipro.controller;

import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.as2c.minipro.util.HttpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ygd
 * @title: LogisticsController
 * @projectName hoshiicloud-root
 * @description: 物流Controller
 * @date 2019/6/10
 */
@Slf4j
@RestController
@RequestMapping("/logistics")
@Api(value = "物流接口", tags = {"物流操作接口"}, produces = MediaType.APPLICATION_JSON_VALUE)
public class LogisticsController {


    @Autowired
    private RedisTemplate<String, Object> RedisTemplate;

    @GetMapping("/query/{orderId}")
    @ApiOperation(value = "查询物流信息", notes = "查询物流信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response queryLogistics(@PathVariable("orderId") String orderId) {

        if (orderId == null) {
            return Response.failed();
        }

        Object object = RedisTemplate.opsForValue().get("logistics~" + orderId);
        if (object == null) {

            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Authorization", "APPCODE " + HttpUtils.appcode);

            Map<String, String> querys = new HashMap<String, String>();
            querys.put("no", orderId.toString());//物流单号
            //querys.put("type", "zto");// 物流公司编码
            try {

                HttpResponse response = HttpUtils.doGet(headers, querys);
                log.info(response.toString()); //输出头部

                String result = EntityUtils.toString(response.getEntity());
                RedisTemplate.opsForValue().set("logistics~" + orderId, result,1, TimeUnit.DAYS);

                return Response.success("查询成功", result);

            } catch (Exception e) {
                log.error("查询物流信息失败：", e);
                return Response.failed();
            }
        }
        return Response.success("查询成功", object);
    }
}
